package model
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	
	import global.GameState;
	
	import model.load.ILoadMessage;
	import model.load.RemoteLoader;
	
	import utils.EnterFrameTimer;

	public class LoaderPoolModel
	{
		private static var instance:LoaderPoolModel;
		
		public function LoaderPoolModel()
		{
			if (instance)
			{
				throw Error("单列!");
			}
			init();
		}
		
		public static function getInstance():LoaderPoolModel
		{
			if (instance == null)instance = new LoaderPoolModel();
			return instance;
		}
		
		//content-------------------------
		
		private var loaders:Array;
		private var loaderMessageStack:Array;
		private var checkMessageTimer:EnterFrameTimer;
		
		
		private function init():void
		{
			initLoaders();
			initCheckMessageTimer();
		}
		
		private function initCheckMessageTimer():void
		{
			checkMessageTimer = new EnterFrameTimer(1000);
			checkMessageTimer.addEventListener(TimerEvent.TIMER,onCheckTimer);
			checkMessageTimer.start();
		}
		
		private function initLoaders():void
		{
			loaders = [];
			loaderMessageStack = [];
		
			for (var i:int=0; i<GameState.LOADER_POOL_MAX; i++)
			{
				var loader:RemoteLoader = new RemoteLoader();
				loaders.push(loader);
			}
		}
		
		private function onCheckTimer(event:TimerEvent):void
		{
			checkLoadMessageStack();
		}
		
		private function checkLoadMessageStack():void
		{
			if (loaderMessageStack.length <= 0)
			{
				return;
			}
			
			for (var i:String in loaders)
			{
				var loader:RemoteLoader = loaders[i];
				if (loader.isIdle)
				{
					loader.updateLoadMessage(loaderMessageStack.shift());
					if (loaderMessageStack.length <= 0)
					{
						return;
					}
				}
			}
		}
		
		public function addLoadMessage(loadMessage:ILoadMessage):void
		{
			if (loadMessage)
			{
				if ( loaderMessageStack.indexOf(loadMessage) >= 0)
				{
					loadMessage.cancel();
				}
				
				if (loadMessage.isImmediate)
				{
					loaderMessageStack.unshift(loadMessage);
					checkLoadMessageStack();
				}
				else
				{
					loaderMessageStack.push(loadMessage);
				}
				
				loadMessage.addEventListener(Event.CANCEL,onLoadMsgCancel);
			}
			
			
		}
		
		private function onLoadMsgCancel(event:Event):void
		{
			removeLoadMessage(event.target as ILoadMessage);
		}
		
		public function removeLoadMessage(loadMessage:ILoadMessage):void
		{
			if (loadMessage)
			{
				loadMessage.removeEventListener(Event.CANCEL,onLoadMsgCancel);
				var index:int = loaderMessageStack.indexOf(loadMessage);
				if (index >= 0)
				{
					loaderMessageStack.splice(index,1);
				}
			}
		}
		
		public function get count():int
		{
			return loaderMessageStack.length;
		}
		
		public function clear():void
		{
			for (var i:String in loaders)
			{
				var loader:RemoteLoader = loaders[i];
				loader.clear();
			}
			loaderMessageStack.length = 0;
		}
		
	}
}